package com.specificgroup.jira.plugin.acpro;

import com.specificgroup.jira.plugin.acpro.exception.AcproXmlException;
import com.specificgroup.jira.plugin.acpro.xml.response.generated.ACProType;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.StringReader;

import com.specificgroup.jira.plugin.acpro.util.HttpUtil;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

/**
 * @author Ivan Holub
 */
public class Main {

    public static void main(String [] args) throws Exception {
        File root = new File("D:\\projects\\jira-acpro-plugin\\trunk\\jira-acpro-plugin\\acproxml");
//        File fileIn = new File(root, "post.xml");
        File fileIn = new File(root, "post_cdata.xml");
//        File fileIn = new File(root, "post_links.xml");
        String request = FileUtils.readFileToString(fileIn, "UTF-8");
        File fileOut = new File(root, "response.xml");
        String response = HttpUtil.post(Constants.ACPRO_POST_URL, request);
        FileUtils.writeStringToFile(fileOut, response, "UTF-8");

        unmarshalResponse(response);
    }

    private static ACProType unmarshalResponse(String response) throws AcproXmlException {
        try {
            JAXBContext context = JAXBContext.newInstance(Constants.XML_RESPONSE_GENERATED_PACKAGE);
            Unmarshaller u = context.createUnmarshaller();
            StringReader reader = new StringReader(response);
            Object obj = u.unmarshal(reader);
            reader.close();
            if (!(obj instanceof JAXBElement)) {
                throw new AcproXmlException("Acpro response xml is not valid");
            }
            JAXBElement root = (JAXBElement) obj;
            Object value = root.getValue();
            if (!(value instanceof ACProType)) {
                throw new AcproXmlException("Acpro response xml is not valid");
            }
            ACProType acProType = (ACProType) value;
            return acProType;
        } catch (JAXBException e) {
            e.printStackTrace();
            throw new AcproXmlException("Acpro response xml is not valid");
        }
    }

}
